﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
public partial class JobManage_BookingJobDetail : BasePage
{
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    IJobHandler jobManage = new JobHandler();
    IBNTruckHandler truckManage = new BNTruckHandler();
    ISystemHandler systemManage = new SystemHandler();
    ISendTruckHandler sendTruckManage = new SendTruckHandler();
    ISyContainerModelHandler containerModelManage = new SyContainerModelHandler();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1062")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    if (strPermission.Contains("1063"))
                    {
                         BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
                         if (orderQuery != null)
                         {
                             if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d"))
                             {
                                 //btnCancel.Visible = true;
                             }
                             else
                             {
                                 //btnCancel.Visible = false;
                             }
                         }

                    }
                    else
                    {
                        //btnCancel.Visible = false;
                    }
                }
            }
            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";

            ViewState["OrderByT"] = "PKID";
            ViewState["AccendingT"] = "desc";
          //  dataBind();
            dataBindDetail(int.Parse(Request["OrderID"]));
            dataBindTruck();
        }
    }

    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }

    public string GetDriver(object id)
    {
        return systemManage.GetDriver(id);
    }

    public string GetType(object typeID)
    {
        string model = string.Empty;
        Sy_ContainerModelQuery query = containerModelManage.GetModel(int.Parse(typeID.ToString()));
        if (query != null)
        {
            return model = query.Model;
        }
        return model;
    }


    //private void dataBind()
    //{
    //    if (Request["OrderID"] != null)
    //    {
    //        BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
    //        if (orderQuery != null)
    //        {
    //            txtOrderNO.Text = orderQuery.OrderNO;
    //            txtBookingNO.Text = orderQuery.BookingNO;
    //            if (orderQuery.BookingDate != DateTime.MinValue)
    //            {
    //                txtBookingDate.Text = orderQuery.BookingDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }
    //            txtStatus.Text = StringUtil.GetShipperOrderStatus(orderQuery.Status);
    //            txtVendor.Text = GetClient(orderQuery.VendorID);
    //            txtArrangeUser.Text = GetUserName(orderQuery.ArrangeUser);
    //            if (orderQuery.ArrangeDate != DateTime.MinValue)
    //            {
    //                txtArrangeDate.Text = orderQuery.ArrangeDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }

    //            if (orderQuery.CheckDate != DateTime.MinValue)
    //            {
    //                txtCheckDate.Text = orderQuery.CheckDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }
    //            txtCheckUser.Text = GetUserName(orderQuery.CheckUser);

    //            if (orderQuery.ConfirmDate != DateTime.MinValue)
    //            {
    //                txtConfimDate.Text = orderQuery.ConfirmDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }
    //            txtConfimUser.Text = GetUserName(orderQuery.ConfirmUser);

    //            if (orderQuery.PrintDate != DateTime.MinValue)
    //            {
    //                txtPrintDate.Text = orderQuery.PrintDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }
    //            txtPrintUser.Text = GetUserName(orderQuery.PrintUser);

    //            if (orderQuery.CancelDate != DateTime.MinValue)
    //            {
    //                txtCancelDate.Text = orderQuery.CancelDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }

    //            txtCancelUser.Text = GetUserName(orderQuery.CancelUser);

    //            txtRemark.Text = orderQuery.Remark;

    //            if (orderQuery.CancelConfirmDate != DateTime.MinValue)
    //            {
    //                txtCancelConfirmDate.Text = orderQuery.CancelConfirmDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }
    //            txtCancelConfirmUser.Text = GetUserName(orderQuery.CancelConfirmUser);

    //            if (orderQuery.CancelArrDate != DateTime.MinValue)
    //            {
    //                txtCancelArrDate.Text = orderQuery.CancelArrDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }
    //            txtCancelArrangeUser.Text = GetUserName(orderQuery.CancelArrangeUser);

    //            if (orderQuery.MateReceiptDate != DateTime.MinValue)
    //            {
    //                txtMateReceiptDate.Text = orderQuery.MateReceiptDate.ToString("yyyy-MM-dd HH:mm:ss");
    //            }
    //            txtMateReceiptConfirmUser.Text = GetUserName(orderQuery.MateReceiptConfirmUser);

    //            dataBindDetail(orderQuery.PKID);
    //            dataBindTruck();
    //        }
    //    }
    //}

    private void dataBindDetail(int orderID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID", orderID.ToString());
        string sqlStr = "select *,Appointament from BN_ShippingOrderDtl,BN_ShippingOrder where BN_ShippingOrder.PKID=BN_ShippingOrderDtl.OrderID and BN_ShippingOrderDtl.OrderID=@OrderID";
        DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvShipperOrderDetailList.DataSource = view;
        gvShipperOrderDetailList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private void dataBindTruck()
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID",Request["OrderID"]);
        string sqlStr = @"select *,LicenseNO,(select Model from Sy_ContainerModel as m where m.PKID =BTDtl.TypeID) as TypeName,(select Name from BN_Driver as T where T.PKID=BTDtl.Driver) as DriverName
            from BN_SendTruck as BT,BN_SendTruckDtl as BTDtl,BN_Truck as T where BT.PKID=BTDtl.SendTruckID and T.PKID =BTDtl.TruckID and BT.OrderID=@OrderID";
        DataTable dt = sendTruckManage.GetList(sqlStr,parms);
        gvTruckList.DataSource = dt;
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderByT"] + " " + ViewState["AccendingT"];
        gvTruckList.DataSource = view;
        gvTruckList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotalTruck.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotalTruck.Text = "0";
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvShipperOrderDetailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvShipperOrderDetailList.PageCount)
            {
                this.gvShipperOrderDetailList.PageIndex = i;
                //数据绑定
                dataBindDetail(int.Parse(Request["OrderID"]));
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvShipperOrderDetailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindDetail(int.Parse(Request["OrderID"]));
    }


    protected void gvShipperOrderDetailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShipperOrderDetailList.PageIndex = e.NewPageIndex;
        dataBindDetail(int.Parse(Request["OrderID"]));
    }
    protected void gvShipperOrderDetailList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBindDetail(int.Parse(Request["OrderID"]));
    }

    protected void lbtnGoTruck_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvTruckList.BottomPagerRow.FindControl("txtPagesTruck"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvTruckList.PageCount)
            {
                this.gvShipperOrderDetailList.PageIndex = i;
                //数据绑定
                dataBindTruck();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);

        }
    }
    protected void ddlPagesTruck_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvTruckList.PageSize = int.Parse(ddlPagesTruck.SelectedValue);
        dataBindTruck();
    }

    protected void gvTruckList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvTruckList.PageIndex = e.NewPageIndex;
        dataBindTruck();
    }
    protected void gvTruckList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderByT"].ToString().ToLower())
        {
            if (ViewState["AccendingT"].ToString().ToLower() == "asc")
            {
                ViewState["AccendingT"] = "desc";
            }
            else
            {
                ViewState["AccendingT"] = "asc";
            }
        }
        else
        {
            ViewState["OrderByT"] = e.SortExpression;
        }

        dataBindTruck();
    }

    private int GetClientID()
    {
        int clientID = 0;
        if (Session["UserID"] != null)
        {
            UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
            if (query != null)
            {
                clientID = query.ClientID;
            }
        }
        return clientID;
    }


    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Request["OrderID"] != null)
        { 
             BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
             if (orderQuery != null)
             {
                 if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d"))
                 {
                     SqlParameter[] parms = new SqlParameter[5];
                     parms[0] = new SqlParameter("@Status",Enums.ShippingOrderStatus.CANCEL.ToString("d"));
                     parms[1] = new SqlParameter("@CancelUser",Session["UserID"].ToString());
                     parms[2] = new SqlParameter("@CancelDate",DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd"));
                     parms[3] = new SqlParameter("@OrderID",Request["OrderID"]);
                     parms[4] = new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.CCANCEL.ToString("d"));//BookingNoteDtl 运输队取消job状态
                     string sqlStr = "update BN_ShippingOrder set Status=@Status,CancelUser=@CancelUser,CancelDate=@CancelDate where PKID=@OrderID;";
                     sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CJCancelDate=@CancelDate,CJCancelUser=@CancelUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID));";

                     if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                     {
                         Jscript.AlertAndRedirectInAjax(Resources.Messages.CancelSuccess, "BookingJobList.aspx", UpdatePanel1);
                     }
                     else
                     {
                         Jscript.AlertInAjax(Resources.Messages.CancelFailed,UpdatePanel1);
                     }
                 }
                 else
                 {
                     Jscript.AlertInAjax(Resources.Messages.JobCancel, UpdatePanel1);
                     return;
                 }
             }
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("BookingJobList.aspx");
    }
}
